package com.dkd.applet.service.impl;

import cn.elegent.ac.ElegentAC;
import cn.elegent.pay.CallBackService;
import com.dkd.applet.common.config.TopicConfig;
import com.dkd.applet.common.constant.OrderStatus;
import com.dkd.applet.common.constant.PayStatus;
import com.dkd.applet.domain.Order;
import com.dkd.applet.domain.dto.VendoutDTO;
import com.dkd.applet.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class CallBackServiceImpl implements CallBackService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ElegentAC elegentAC;
    @Override
    public void successPay(String orderSn) {
        log.info("支付成功回调{}", orderSn);

        Order order = orderService.getByOrderNo(orderSn);
        if (order != null) {
            if (order.getStatus().equals(OrderStatus.ORDER_STATUS_CREATE)) {
                order.setStatus(OrderStatus.ORDER_STATUS_PAYED); //订单状态  已支付
                order.setPayStatus(PayStatus.PAY_STATUS_PAYED);//支付状态  成功
                orderService.updateById(order);
                // 发货
                 VendoutDTO vendoutDTO = new VendoutDTO();
                vendoutDTO.setOrderNo(order.getOrderNo());
                vendoutDTO.setSkuId(order.getSkuId());
                vendoutDTO.setChannelCode(order.getChannelCode());
                vendoutDTO.setInnerCode(order.getInnerCode());
                elegentAC.publish(TopicConfig.getVendoutTopic(order.getInnerCode()), vendoutDTO);
            }
        }
    }

    @Override
    public void failPay(String orderSn) {
        log.info("支付失败回调", orderSn);
    }
/**
 * 修改订单状态为退款完成
 * @param orderSn
 */
    @Override
    public void successRefund(String orderSn) {
        log.info("退款成功回调！" + orderSn);
        Order order = orderService.getByOrderNo(orderSn);
        if (order != null) {
            order.setPayStatus(PayStatus.PAY_STATUS_REFUNDIED);
            orderService.updateById(order);
        }
    }
/**
 * 退款失败打日志记录--修改状态为已支付
 * @param orderSn
 */
    @Override
    public void failRefund(String orderSn) {
        log.info("退款失败回调！" + orderSn);
    log.info("退款成功回调！" + orderSn);
        Order order = orderService.getByOrderNo(orderSn);
        if (order != null) {
            order.setPayStatus(PayStatus.PAY_STATUS_REFUNDING);
            orderService.updateById(order);
        }
    }
}